Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

311
Visualizações
CastError: Cast to [undefined] failed for value "[]" (type string) at path "comments.undefined"

I'm quite new to node and mongoose. I'm trying to do a project using them, but i'm running into an error while trying to populate. The comment is saved to the Comment schema perfectly, but throws an error when i reference it Organization Schema.Please advise me on what i'm doing wrong. Any form of assistance will be appreciated.

// Post route for comment(on the Organization's profile page)
router.post('/comment/:id', ensureAuthenticated,(req, res) =>{
  let id = req.params.id;
  console.log(mongoose.Types.ObjectId.isValid(id))
  const commentObject = new Comment({
    sender: 'Fred kimani', 
    commentBody: req.body.commentBody
  })
  console.log(commentObject);
  commentObject.save((err, result) =>{
    if(err){console.log(err)}
    else{
      Organization.findByIdAndUpdate(id, {$push: {comments: result}}, {upsert: true}, (err, organization) =>{
        if(err){console.log(err)}
        else{
          console.log('======Comments====')
        }
      })
      res.redirect('/users/organizationprofilepage/:id')
    }
  })
});

//Organization Schema

const mongoose = require('mongoose');

const OrganizationSchema = new mongoose.Schema({

  organization_name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  },
  category: {
    type: String,
    required: true
  },
  isApproved: {
    type: Boolean,
    default: false
  },
  image:{
    type:String,
    required:true
  },
  description: {
    type: String,
    required: true,
  }, 
  comments: [{
    type: mongoose.Types.ObjectId,
    ref: 'Comment'
  }],
  
},
//{ typeKey: '$type' }
);


OrganizationSchema.statics.getOrganizations = async function () {
  try {
    const organizations = await this.find();
    return organizations;
  } catch (error) {
    throw error;
  }
}

//defines the layout of the db schema

const Organization = mongoose.model('0rganization', OrganizationSchema);
module.exports = Organization;

//Comment schema

const mongoose = require('mongoose');


const CommentSchema =  mongoose.Schema({

    sender: {
      type: String,
    }, 
    commentBody: { 
      type: String,
      required: false,
    },
    date: {
      type: Date,
      default: Date.now
    },
  })


  CommentSchema.statics.getComments= async function () {
    try {
      const comments = await this.find();
      return comments ;
    } catch (error) {
      throw error;
    }
  }

  const Comment= mongoose.model('Comment', CommentSchema);
  module.exports = Comment;

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

  1. Try to change the comments type to mongoose.Schema.Types.ObjectId:
comments: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Comment',
    },
  ],
  1. Try to push the new commend _id into the Organization object after its creation, not the whole object:
commentObject.save((err, result) => {
  if (err) {
    console.log(err);
  } else {
    Organization.findByIdAndUpdate(
      id,
      { $push: { comments: result._id } }, // <- Change this line
      { upsert: true },
      (err, organization) => { }
    );
    ...
  }
});
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda